package cn.tannn.ops.pwd.controller;


import cn.tannn.jdevelops.annotations.web.mapping.PathRestController;
import cn.tannn.jdevelops.jpa.result.JpaPageResult;
import cn.tannn.jdevelops.result.response.ResultPageVO;
import cn.tannn.jdevelops.result.response.ResultVO;
import cn.tannn.ops.pwd.controller.dto.CreateKeePass;
import cn.tannn.ops.pwd.controller.dto.KeePassPage;
import cn.tannn.ops.pwd.controller.dto.ViewPass;
import cn.tannn.ops.pwd.controller.vo.KeePassVO;
import cn.tannn.ops.pwd.controller.vo.RSAKey;
import cn.tannn.ops.pwd.entity.KeePassEntity;
import cn.tannn.ops.pwd.enums.EncryptType;
import cn.tannn.ops.pwd.enums.KeePassStatus;
import cn.tannn.ops.pwd.service.KeePassService;
import cn.tannn.ops.pwd.strategy.EncryptContext;
import cn.tannn.ops.util.RasUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.Optional;

/**
 * 密码管理器
 *
 * @author tnnn
 * @version V1.0
 * @date 2023-02-20 09:27
 */
@PathRestController("password")
@RequiredArgsConstructor
public class KeePassController {

    private final KeePassService keePassService;


    /**
     * 查询列表
     *
     * @param pass CreateKeePass
     * @return String
     */
    @PostMapping("/page")
    public ResultPageVO<KeePassVO, JpaPageResult<KeePassVO>> findPage(@RequestBody KeePassPage pass) {
        Page<KeePassEntity> pages = keePassService.findPage(pass, pass.getPage());
        return ResultPageVO.success(JpaPageResult.toPage(pages,KeePassVO.class), "查询成功");
    }


    /**
     * 新增密码
     *
     * @param pass CreateKeePass
     * @return String
     */
    @PostMapping("/create")
    public ResultVO<String> createPassword(@RequestBody @Valid CreateKeePass pass) throws IllegalAccessException {
        KeePassEntity save = pass.to(KeePassEntity.class);
        save.setStatus(KeePassStatus.VALID);
        EncryptType encryptType = EncryptType.valueOf(pass.getEncryptTypeStr());
        save.setEncryptType(encryptType);
        String encrypt = new EncryptContext(encryptType)
                .executeEncrypt(pass.getSecret(), pass.getPassword(), pass.getEncryptCount());
        save.setPassword(encrypt);
        keePassService.saveOne(save);
        return ResultVO.successMessage("新增成功");
    }

    /**
     * 查看密码
     *
     * @param id     密码数据id
     * @param secret 用户自己保管的密钥
     * @return 明文密码
     */
    @PostMapping("/view/{id}")
    public ResultVO<String> viewPassword(@PathVariable("id") Long id, @RequestBody @Valid  ViewPass secret) throws IllegalAccessException {
        KeePassEntity findId = keePassService.findById(id).orElseThrow(() -> new IllegalArgumentException("非法的id"));
        EncryptContext encryptContext = new EncryptContext(findId.getEncryptType());
        String decrypt = encryptContext.executeDecrypt(secret.getSecret(), findId.getPassword(), findId.getEncryptCount());
        return ResultVO.success("查询成功", decrypt);
    }

    /**
     * 删除 （有效的删除会放到回收站，回收站的删除会直接删了）
     *
     * @param id 密码数据id
     * @return String
     */
    @DeleteMapping("/delete/{id}")
    public ResultVO<String> deletePassword(@PathVariable("id") Long id) {
        Optional<KeePassEntity> exist = keePassService.findById(id);
        if (exist.isPresent()) {
            KeePassStatus status = exist.get().getStatus();
            keePassService.deleteById(status, id);
        }
        return ResultVO.successMessage("删除成功");
    }


    /**
     * 获取rsa 公私钥用于加密和解密，用户保存私钥用于解密。公钥进行加密。记得保存哦
     *
     * @return RSAKey
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    @GetMapping("/rsa/key")
    public ResultVO<RSAKey> rsaKey() throws NoSuchAlgorithmException {
        return ResultVO.success("创建成功,请妥善保管！", RasUtil.getRSAKeyString(1024));
    }

    //---------------------------规划接口-------------------------------------
    // 1. 导入密码数据
    // 2. 导出密码数据
    // 3. 下载离线解密exe


}
